<template>
  <div class="container-wrapper">
    <div class="auth-container">
      <h2>{{ isLogin ? "登录" : "注册" }}</h2>

      <!-- 用户名输入框 -->
      <div>
        <input v-model="username" type="text" placeholder="账号" />
      </div>

      <!-- 密码输入框 -->
      <div>
        <input v-model="password" type="password" placeholder="密码" />
      </div>

      <!-- 根据是否为登录页面显示不同的输入框或选择框 -->
      <div v-if="isLogin">
        <select v-model="selectedRole">
          <option value="0">用户</option>
          <option value="1">医生</option>
          <option value="2">管理员</option>
        </select>
      </div>
      <div v-else>
        <input v-model="nickname" type="text" placeholder="用户昵称" />
        <input v-model="tel" type="text" placeholder="手机号" />
      </div>

      <!-- 登录与注册按钮 -->
      <div v-if="isLogin">
        <button @click="login">登录</button>
        <button @click="toggleAuthMode">注册</button>
        <span v-if="isLogin" class="forgot-password" @click="forgotPassword">
          忘记密码?
        </span>
      </div>
      <div v-else>
        <button @click="register">注册</button>
        <button @click="toggleAuthMode">返回</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import axios from "axios";
import { useUserStore } from '../store/userInfo';

const userStore = useUserStore();
// 判断当前页面是登录还是注册
const isLogin = ref(true);
// 用户账号
const username = ref("");
// 用户密码
const password = ref("");
// 用户角色（权限）
const selectedRole = ref("0");
// 用户昵称（仅在注册时使用）
const nickname = ref("");
// 用户手机号
const tel = ref("");

const router = useRouter();

// 切换登录和注册模式
function toggleAuthMode() {
  isLogin.value = !isLogin.value;
}

// 登录接口
async function login() {
  try {
    let response;

    // 判断用户选择的权限，调用相应的接口
    if (selectedRole.value === "0") {
      // 用户登录接口
      response = await axios.post("api/patients/login", {
        userName: username.value,
        userPasswd: password.value,
      });
      response.data.data.jurisdiction = 0
    } else {
      // 医生或管理员登录接口
      response = await axios.post("api/hospital/login", {
        userName: username.value,
        userPasswd: password.value,
        jurisdiction: selectedRole.value,
      });

    }

    if (response.data && response.data.code === 200) {
      // 登陆成功
      response.data.data.flag = true
      const loggedInUser = response.data.data

      // 将用户信息存储在localStorage
      localStorage.setItem(
        "loggedInUser",
        JSON.stringify({
          id: loggedInUser.id,
          nickName: loggedInUser.nickName,
          role: selectedRole.value,
        })
      )

  // 将用户的所有信息存储在userInfo里
      userStore.setUserInfo(response.data.data);

      console.log("loginUser", userStore.userInfo)

      // 登录成功后跳转到系统首页
      router.push("/home");

    } else {
      alert("账号或密码错误，请重新输入");
    }
  } catch (error) {
    console.log(error)
    alert("请求失败，请检查您的网络连接");
  }
}

// 注册接口
async function register() {
  if (username.value && password.value && nickname.value) {
    try {
      const response = await axios.post("api/patients/addUser", {
        userName: username.value,
        userPasswd: password.value,
        nickName: nickname.value,
        telphone:tel.value
      });

      if (response.data && response.data.code === 200) {
        // 注册成功后重置表单并切换回登录页面
        username.value = "";
        password.value = "";
        nickname.value = "";
        toggleAuthMode();
      } else {
        alert("注册失败，请重试");
      }
    } catch (error) {
      alert("请求失败，请检查您的网络连接");
    }
  } else {
    alert("请填写所有字段");
  }
}

// 忘记密码提示
function forgotPassword() {
  alert("你还好意思忘记？");
}

// 获取所有用户数据（备用）
async function getUsers() {
  axios.get("api/hospital/getAllUser")
    .then(response => {
      console.log("获取的用户数据:", response.data.data);
    })
    .catch(error => {
      console.error("获取用户数据时出错:", error);
    });
}

// 页面挂载时调用 getUsers 函数（可选）
onMounted(() => {
  // 清除本地存储空间
  // userStore.userInfo.flag = false
  localStorage.removeItem('loggedInUser');
  getUsers();
});

</script>

  
<style scoped>
.container-wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background-image: url(https://img1.baidu.com/it/u=1153393790,3891590548&fm=253&fmt=auto&app=138&f=PNG?w=860&h=430);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}

.auth-container {
  width: 300px;
  height: 300px;
  margin: auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
  text-align: center;
  background-color: rgba(245, 243, 243, 0.5);
  box-shadow: 5px 5px 10px rgba(0, 0, 0, 0.5);
}

input {
  width: 90%;
  padding: 10px;
  margin: 5px 0;
  font-size: 10px;
}

select {
  width: 98%;
  padding: 10px;
  margin: 5px 0;
  font-size: 10px;
}

button {
  width: 98%;
  padding: 10px;
  margin: 10px 0;
  background-color: rgb(51, 51, 51);
  border: none;
  border-radius: 5px;
  color: aliceblue;
}

.error {
  color: red;
  margin-top: 10px;
}

.forgot-password {
  color: #423d3d;
  cursor: pointer;
  text-align: right;
  margin-top: 10px;
  font-size: 13px;
}
</style>